<?php

namespace wangk\throttle\throttle;

class LeakyBucket extends ThrottleAbstract
{

    public function allowRequest(string $key, float $micron, int $max_requests, int $duration, $cache): bool
    {
        if ($max_requests <= 0) return false;

        $last_time = (float)$cache::get($key, 0);      // 最近一次请求
        $rate      = (float)$duration / $max_requests;       // 平均 n 秒一个请求
        if ($micron - $last_time < $rate) {
            $this->cur_requests = 1;
            $this->wait_seconds = ceil($rate - ($micron - $last_time));
            return false;
        }

        $cache::set($key, $micron, $duration);
        return true;
    }
}